Repository navigation
Performance improvements and basic speculative decoding implementation - #2
Merged
Merged
Conversation
The upstream merge (bc3c20e) collapsed all sampler selection into TopPSampler, which runs argSort on the full vocabulary (131K+ for Qwen3.5). This caused a 4x speed regression: 3.1 tok/s vs ~13 tok/s. Restore the smarter selection from our pre-merge code: - topK > 0: TopKTopPSampler (sorts only topK candidates first) - topP only: TopPSampler (sorts full vocab, unavoidable) - neither: CategoricalSampler (no sorting) For Qwen3.5 4B 4-bit with topK=20: 3.1 → 13.7 tok/s (4.4x faster).
Replace CPU-side [Int] token buffers with GPU-resident TokenRing struct that uses MLX.where mask operations for writes — no token.item(Int.self) calls that force CPU to wait for GPU results. TokenRing: shared ring buffer using MLXArray.arange() positions and MLX.where for GPU-only append. Bulk-loads prompt tokens efficiently. RepetitionContext, PresencePenaltyContext, FrequencyPenaltyContext: all rewritten to use TokenRing. FrequencyPenaltyContext now uses GPU histogram via .at[].add() instead of CPU dict counting. TopPSampler: rewritten to work in log-space with separate applyTopP, applyMinP, applyTopK filters matching Python mlx-lm ordering. Uses putAlong/takeAlong for scatter operations. Removes TopKTopPSampler (unified into TopPSampler). Based on approach from upstream PR #147. Preserves Sam-specific additionalProcessors and reasoningEffort fields. Expected: ~35% tok/s improvement with penalty processors active.
loadPrompt received multi-dimensional prompt tokens (e.g. [1, 1454]) but used dim(0) which returned the batch dimension (1), not the sequence length. This caused the buffer to be allocated with the wrong size, leading to shape mismatch in append() when positions array couldn't broadcast with the oversized buffer. Fix: reshape(-1) first, then measure dim(0) on the flattened array.
Port key optimizations from upstream PR #147: - Work in log-space throughout (single logSoftmax vs multiple softmax) - Use argPartition for top-k (O(V) vs O(V log V) full sort) - Use -Float.infinity instead of -1e9 for proper categorical masking - Pre-compute filter threshold arrays only when filters are active - Cleaner code structure matching Python mlx-lm sample_utils.py
Matches Python mlx-lm behavior of calling mx.clear_cache() during long generation runs to prevent memory fragmentation. Without this, GPU memory allocations accumulate and can cause pressure on memory-constrained systems.
Add MLX.Memory.clearCache() every 256 tokens during generation, matching Python mlx-lm behavior to prevent memory fragmentation. Attempted mx.compile() for sampler functions but reverted — the Swift compile() implementation uses evalLock which deadlocks with asyncEval() in the TokenIterator generation loop. This is an upstream mlx-swift issue where CompiledFunction.innerCall holds evalLock while mlx_closure_apply triggers evaluation that also needs the eval pipeline.
ekryski
force-pushed
the
ek/perf-sampler
branch
from
March 29, 2026 22:50
cf8f79a to
5a6879d
Compare
TheTom
referenced
this pull request
in TheTom/mlx-swift-lm
Apr 5, 2026
Performance improvements and basic speculative decoding implementation
5 tasks
ekryski
added a commit
that referenced
this pull request
May 8, 2026
feat(lfm2): consolidate text decoder into MLXLMCommon namespace (WS-C #2)
ekryski
added a commit
that referenced
this pull request
May 12, 2026
Spec was originally written as a multi-phase plan with phase 1 (protocol) landing first and phases 2 (kernel) / 3 (iterator) deferred to follow-ups. The actual implementation consolidated phases 1-3 into PR #143 with a 4-repo native-kernel chain (mlx#26 → mlx-c#14 → mlx-swift#25 → mlx-swift-lm#143). Status header now reflects: - Phases 1+2+3: DONE, GDN coverage (Qwen 3.5 / 3.6) live. - Phase 4 (DFlash iterator): DEFERRED — picks up when spec 015 phase 1 merges. - Phase 5 (PrefixKVCache): DEFERRED — picks up on spec 017's branch. - Mamba / Mamba 2: opted out via canStateReplay=false; future-work options ranked in §"Mamba / Mamba 2 follow-up (post-MVP)". Risks section audited against the actual implementation — every risk now has an explicit "mitigated" or "deferred + how" note: - #1 fp32 numerical equivalence: mitigated via state-in-fp32 throughout the recurrence; 4 equivalence tests lock it. - #2 memory pressure cap: no longer needed after Option A's per-round recording (50ba77f); 30 entries per round, not 360. - #3 Mamba variants: opted out cleanly; future work documented. - #4 spec-006 hierarchy: integration complete, no friction. - #5 masked-timestep correctness: kernel adopts 3217e15 pattern from day 1; verified at gated_delta_replay.metal:200-216. Gap noted: masked-replay unit test deferred (no live caller passes mask != nil). - #6 branchless discipline: c9f992e pattern adopted. - #7 NEW — off-by-one in iterator → protocol translation: documented with the fix and its bench impact (35B-A3B D=12 acceptance 34% → 92%). Files-touched table rewritten with final paths + the 4-repo chain split. Iterator-changes pseudo-code updated to match the shipped single-dispatch shape (helper routes full vs partial accept internally) and the +1 translation is now called out explicitly. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski
added a commit
that referenced
this pull request
May 12, 2026
Spec was originally written as a multi-phase plan with phase 1 (protocol) landing first and phases 2 (kernel) / 3 (iterator) deferred to follow-ups. The actual implementation consolidated phases 1-3 into PR #143 with a 4-repo native-kernel chain (mlx#26 → mlx-c#14 → mlx-swift#25 → mlx-swift-lm#143). Status header now reflects: - Phases 1+2+3: DONE, GDN coverage (Qwen 3.5 / 3.6) live. - Phase 4 (DFlash iterator): DEFERRED — picks up when spec 015 phase 1 merges. - Phase 5 (PrefixKVCache): DEFERRED — picks up on spec 017's branch. - Mamba / Mamba 2: opted out via canStateReplay=false; future-work options ranked in §"Mamba / Mamba 2 follow-up (post-MVP)". Risks section audited against the actual implementation — every risk now has an explicit "mitigated" or "deferred + how" note: - #1 fp32 numerical equivalence: mitigated via state-in-fp32 throughout the recurrence; 4 equivalence tests lock it. - #2 memory pressure cap: no longer needed after Option A's per-round recording (50ba77f); 30 entries per round, not 360. - #3 Mamba variants: opted out cleanly; future work documented. - #4 spec-006 hierarchy: integration complete, no friction. - #5 masked-timestep correctness: kernel adopts 3217e15 pattern from day 1; verified at gated_delta_replay.metal:200-216. Gap noted: masked-replay unit test deferred (no live caller passes mask != nil). - #6 branchless discipline: c9f992e pattern adopted. - #7 NEW — off-by-one in iterator → protocol translation: documented with the fix and its bench impact (35B-A3B D=12 acceptance 34% → 92%). Files-touched table rewritten with final paths + the 4-repo chain split. Iterator-changes pseudo-code updated to match the shipped single-dispatch shape (helper routes full vs partial accept internally) and the +1 translation is now called out explicitly. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
8 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Proposed changes
Performance improvements and basic speculative decoding implementation
Checklist
Put an
xin the boxes that apply.pre-commit run --all-filesto format my code / installed pre-commit prior to committing changes